package com.lanhao.aot.carrierintegration.hfd;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class HfdInvokeUtil {
	private static final Logger LOG = LoggerFactory.getLogger(HfdInvokeUtil.class);
	// https://ws.hfd.co.il/RunCom.WebAPI/api/v1/shipments/create
//	public static final String BASE_URL = "https://test.hfd.co.il";
//	public static final int ClientNumber = 5997;
//	public static final String TOKEN = "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwczovL3J1bmNvbS5jby5pbC9jbGFpbXMvY2xpZW50bm8iOiI1OTk3IiwiaHR0cHM6Ly9ydW5jb20uY28uaWwvY2xhaW1zL3BocmFzZSI6IjBhYWQ0ZTY5LThhYzItNDA1NC1iZWMzLTdhMGIyODZjZTdiOCIsImV4cCI6MTcyOTQ5NDI0MSwiaXNzIjoiaHR0cHM6Ly9ydW5jb20uY28uaWwiLCJhdWQiOiJodHRwczovL3J1bmNvbS5jby5pbCJ9.v54GKSaIKl2OdrBR_lITIFzrfq8sHvOoJY4HSE7n5FI";
	
	public static final String BASE_URL = "https://ws.hfd.co.il";
	public static final int ClientNumber = 10654;
	public static final String TOKEN = "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwczovL3J1bmNvbS5jby5pbC9jbGFpbXMvY2xpZW50bm8iOiIxMDY1NCIsImh0dHBzOi8vcnVuY29tLmNvLmlsL2NsYWltcy9waHJhc2UiOiI1NzUwNTA5YS1kNDgzLTQ0ODEtOWQ3Ni0xYjc0NTQwNzRhNzciLCJleHAiOjE3NjIzNTM0NjIsImlzcyI6Imh0dHBzOi8vcnVuY29tLmNvLmlsIiwiYXVkIjoiaHR0cHM6Ly9ydW5jb20uY28uaWwifQ.nY1IcnPTV8AJPllyxfMDYXlYLqEfOcQ2z4TkiiU9zGI";
	
	public static final String CREATE_URL = BASE_URL + "/RunCom.WebAPI/api/v1/shipments/create";
	public static final String PRINT_URL = BASE_URL + "/RunCom.Server/Request.aspx?APPNAME=run&PRGNAME=ship_print_ws&ARGUMENTS=-N";
	public static final String MesiraIsuf = "איסוף"; // איסוף for returns   מסירה for deliveries
	public static final int ShipmentTypeCode = 50;
//	public static final int StageCode = 0;
	public static final int CargoTypeHaloch = 11;
//	public static final int CargoTypeHazor = 11;
	public static final String AutoBindPudo = "Y";
	
	public static void main(String[] args) {
//		createShipment();
		Map<String, String> header = Maps.newHashMap();
		header.put("Authorization", TOKEN);
		List<String> numList = Lists.newArrayList();
		numList.add("62283195");
		for (String num : numList) {
			downloadFile(header, Long.valueOf(num));
		}
		
		// update eb_task t set t.label_url = CONCAT(CONCAT('https://res-oss.anhelogistics.com/eLabel/HFD/2024/03/06/HFD_', t.mail_no), '.PDF') where t.carrier = 'HFD' and t.label_url like 'https://ws.hfd.co.il/%';
	}

	public static void createShipment() {
		JSONObject request = new JSONObject();
		request.put("ClientNumber", ClientNumber); // Customer number (get it from HFD)
		/**
		 * איסוף for returns   מסירה for deliveries
		 */
//		request.put("MesiraIsuf", "איסוף");
		request.put("MesiraIsuf", MesiraIsuf);
		request.put("ShipmentTypeCode", ShipmentTypeCode); // Shipment type - get the code from HFD
		/**
		 * Shipment stage Consult with the shipping company which code to send
		 */
		request.put("StageCode", null);
		request.put("OrdererName", "AnHe"); // Your company name
		request.put("SubCharge", null); 
		/**
		 * Shipped cargo type - get the code from HFD
		 */
		request.put("CargoTypeHaloch", CargoTypeHaloch);
		/**
		 * Returned cargo type (relevant for returns only) - get the code from HFD
		 */
		request.put("CargoTypeHazor", null);
		request.put("PacksHaloch", null); // Number of packages to be delivered
		/**
		 * Number of returned packages (relevant for returns only)
		 */
		request.put("PacksHazor", 1);
		request.put("RakazCode", 0);
		request.put("NameTo", "KunKun"); // Consignee's name
		request.put("PassportNum", null);
		request.put("CityCode", null); // City/settlement code - optional
		request.put("CityName", "Tel aviv"); // City/settlement name
		request.put("StreetCode", null); // Street code
		/**
		 * This field can contain street name together with building number, in this case houseNum can be left blank
		 */
		request.put("StreetName", "Arolozorov 44"); //
		request.put("HouseNum", null); // Building No
		request.put("Entrance", null); // Entrance No
		request.put("Floor", null); // Floor No
		request.put("Apartment", null); // Apartment No
		request.put("ZipCode", null); // 
		request.put("TelFirst", ""); // Primary phone number (cellular)
		request.put("TelSecond", null); // Additional phone number
		request.put("AddressRemarks", ""); // Address remarks
		request.put("ShipmentRemarks", ""); // Additional shipment remarks (if any)
		/**
		 * Your reference number for the shipment You can also send several reference numbers separated by ":"
		 */
		request.put("ReferenceNum1", ""); // 
		request.put("ReferenceNum2", ""); // Second reference number for the shipment.
		/**
		 * If you want the shipment to be picked up on a specific date which is more than a day away from the date of the request, you can specify a date in this field.
		 */
		request.put("FutureDate", null);
		/**
		 * If you want the shipment to be picked up at a specific hour which is more than a day away from the date of the request, you can specify time in this field.
		 */
		request.put("FutureTime", null);
		request.put("DeliveryDate", null);
		request.put("DeliveryTimeSlot", null);
		/**
		 * Source pickup point – relevant for returns only
		 */
		request.put("PudoCodeOrigin", null);
		/**
		 * 	Destination pickup point
			Relevant only for shipments to pickup points
			Please fill in if your customer has chosen a pickup point on your website
		 */
		request.put("PudoCodeDestination", null);
		/**
		 * 	Our system can assign a pickup point for a shipment automatically, based on a consignee’s address (the closest working point will be assigned).
			N = Do not assign (default)
			Y = Assign any type (store or locker)
		 */
		request.put("AutoBindPudo", AutoBindPudo);
		request.put("Email", "");	// Consignee's email
		request.put("ProductsPrice", 0.0); // Products price
		request.put("ProductPriceCurrency", null); // Currency
		request.put("ShipmentWeight", 0.0); // Parcel weight (in grams)
		request.put("OrderItems", null);
		request.put("Govina", null);
		request.put("STW", null);
		
		Map<String, String> header = Maps.newHashMap();
		header.put("Authorization", TOKEN);
		LOG.info("获取以色列面单url={}，request={}", CREATE_URL, request.toJSONString());
		String respBody = HttpRequest.post(CREATE_URL).setConnectionTimeout(5000).setReadTimeout(15000).addHeaders(header).body(request.toJSONString()).execute().body();
		LOG.info("获取以色列面单获取响应respBody={}", respBody);
		// 错误：{"shipmentNumber":0,"randNumber":"","referenceNumber1":"","referenceNumber2":"","deliveryLine":0,"deliveryArea":0,"errorCode":"5000","errorMessage":"סוג משלוח זה מחייב נקודת חלוקה,-","existingShipmentNumber":0,"sortingCode":0,"pickUpCode":0}
		// 成功：{"shipmentNumber":25446004,"randNumber":"15425446004375","referenceNumber1":"","referenceNumber2":"","deliveryLine":502,"deliveryArea":0,"errorCode":"NULL","errorMessage":"NULL","existingShipmentNumber":0,"sortingCode":102,"pickUpCode":208,"pickUpName":"לי פון","pickUpAddress":"שעות פתיחה:א-ה 09:30-17:30 יום ו 09:30-14:00"}
		JSONObject respBodyObject = JSON.parseObject(respBody);
		Long shipmentNumber = respBodyObject.getLong("shipmentNumber");
		if (shipmentNumber != 0) {
			LOG.info("获取以色列面单成功，shipmentNumber={}", shipmentNumber);
			// 调用25446001获取标签文件
			
		} else {
			String errorMessage = respBodyObject.getString("errorMessage");
			LOG.info("获取以色列单号失败，errorMessage={}", errorMessage);
		}
	}
	
	public static void downloadFile(Map<String, String> header, Long shipmentNumber) {
		String printUrl = PRINT_URL + shipmentNumber;
		HttpResponse execute = HttpRequest.get(printUrl).addHeaders(header).execute();
		String contentType = execute.header("Content-Type");
		long size = execute.writeBody(new File("D:/hfd/HFD_" + shipmentNumber + ".pdf"));
		LOG.info("获取以色列标签{}，contentType={}, 写入文件大小size={}", shipmentNumber,  contentType, size);
	}
}
